﻿using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using RestSharp;
using WhallaToolkit.ShareServices.Helpers;
using WhallaToolkit.ShareServices.Interfaces;
using WhallaToolkit.ShareServices.Models.AccessTokens;

namespace WhallaToolkit.ShareServices.Services
{
    public class FacebookServices : IShareService
    {
        #region Constructor 

        public FacebookServices(FacebookAccessToken token)
        {
            this.Token = token;
        }

        #endregion

        #region Properties

        public AccessToken Token { get; set; }

        #endregion

        #region Methods

        internal static Uri GetLoginUrl()
        {
            return new Uri("https://m.facebook.com/dialog/oauth?client_id=" + PortalsResources.FacebookAppId + "&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=" + PortalsResources.FacebookScope + "&display=touch",UriKind.Absolute);
        }

        internal static String GetAccessTokenRequestUrl(string code)
        {
            return "https://graph.facebook.com/oauth/access_token?client_id=" + PortalsResources.FacebookAppId + "&redirect_uri=https://www.facebook.com/connect/login_success.html&client_secret=" + PortalsResources.FacebookClientSecret + "&code=" + code;
        }

        public void PostMessageOnWall(string message, UploadStringCompletedEventHandler handler)
        {
            WebClient client = new WebClient();

            client.UploadStringCompleted += handler;
            client.UploadStringAsync(new Uri("https://graph.facebook.com/me/feed"), "POST", "message=" + HttpUtility.UrlEncode(message)
                + "&access_token=" + Token.Token);
        }

        public async Task<bool> PostMediaOnFacebookAsync(Stream photoSource, string message)
        {
            photoSource.Seek(0, SeekOrigin.Begin);
            MemoryStream ms = photoSource.ConvertStreamToMemoryStream();
            byte[] imageBytes = ms.ToArray();
            var clientRest = new RestClient("https://graph.facebook.com");
            var request = new RestRequest("me/photos", Method.POST);
            request.AddParameter("access_token", Token.Token);
            request.AddParameter("message", message);
            request.AddFile("filename", imageBytes, "photo");
            var response = await clientRest.GetResponseAsync(request);
            return response.ResponseStatus == ResponseStatus.Completed;
        }

        public async Task<bool> PostMediaOnFacebookAsync(BitmapImage photoSource, string message)
        {
            WriteableBitmap bmp = new WriteableBitmap(photoSource);
            Stream imageStream = new MemoryStream();
            bmp.SaveJpeg(imageStream, photoSource.PixelWidth, photoSource.PixelHeight, 0, 100);
            imageStream.Seek(0, SeekOrigin.Begin);
            byte[] imageBytes = imageStream.ConvertStreamToMemoryStream().ToArray();
            var clientRest = new RestClient("https://graph.facebook.com");
            var request = new RestRequest("me/photos", Method.POST);
            request.AddParameter("access_token", Token.Token);
            request.AddParameter("message", message);
            request.AddFile("filename", imageBytes, "photo");
            var response = await clientRest.GetResponseAsync(request);
            return response.ResponseStatus == ResponseStatus.Completed;
        }

        public async Task<bool> PostMessageOnFacebookAsync(string message)
        {
            var clientRest = new RestClient("https://graph.facebook.com");
            var request = new RestRequest("me/feed", Method.POST);
            request.AddParameter("access_token", Token.Token);
            request.AddParameter("message", message);
            var response = await clientRest.GetResponseAsync(request);
            return response.ResponseStatus == ResponseStatus.Completed;
        }

        public async Task<bool> PostLinkOnFacebookAsync(string link, string message)
        {
            var clientRest = new RestClient("https://graph.facebook.com");
            var request = new RestRequest("me/feed", Method.POST);
            request.AddParameter("access_token", Token.Token);
            request.AddParameter("message", message);
            request.AddParameter("link", link);
            var response = await clientRest.GetResponseAsync(request);
            return response.ResponseStatus == ResponseStatus.Completed;
        }

        #endregion

        #region Interface Methods
        public void SetToken(AccessToken tokens)
        {
            Token = tokens;
        }
        public async Task<bool> PostMediaOnSocialTask(AccessToken tokens, Stream photoSource, string description)
        {
                Token =(FacebookAccessToken) tokens;
                return await PostMediaOnFacebookAsync(photoSource, description);
        }

        public async Task<bool> PostMediaOnSocialTask(Stream photoSource, string description)
        {
            return await PostMediaOnFacebookAsync(photoSource, description);
        }

        public async Task<bool> PostMediaOnSocialTask(AccessToken token, System.Windows.Media.Imaging.BitmapImage photoSource, string description)
        {
            Token = (FacebookAccessToken)token;
            return await PostMediaOnFacebookAsync(photoSource, description);
        }

        public async Task<bool> PostMediaOnSocialTask(System.Windows.Media.Imaging.BitmapImage photoSource, string description)
        {
            return await PostMediaOnFacebookAsync(photoSource, description);

        }

        public async Task<bool> PostMessageOnSocialTask(string description)
        {
            return await PostMessageOnFacebookAsync(description);
        }

        public async Task<bool> PostLinkOnSocialTask(AccessToken tokens, string link, string description)
        {
            Token = (FacebookAccessToken)tokens;
            return await PostLinkOnSocialTask(link, description);
        }

        public async Task<bool> PostLinkOnSocialTask(string link, string description)
        {
            return await PostLinkOnFacebookAsync(link, description);
        }
        #endregion
    }
}
